package io.qifan.desktop.server.controller.websocket;

import io.qifan.desktop.api.protocol.response.BaseResponse;
import io.qifan.desktop.api.protocol.request.ConnectReqMsg;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.security.Principal;

@Controller
@Slf4j
@RequiredArgsConstructor
public class SocketConnectController {

    private final SimpMessagingTemplate template;


    @MessageMapping("/desktop/connect/request")
    public void connect(@Payload ConnectReqMsg reqMsg, Principal principal) {
        log.info("当前设备：{}", principal.getName());
        log.info("设备：{} 要控制设备：{}，密码是：{}", reqMsg.getLocalDeviceId(),
                reqMsg.getRemoteDeviceId(),
                reqMsg.getPassword());
        // 将消息转发给订阅客户端
        template.convertAndSendToUser(String.valueOf(reqMsg.getRemoteDeviceId()), "/topic/desktop/connect/request", reqMsg);

    }

    @MessageMapping("/desktop/response")
    public void connectResponse(@Payload BaseResponse respMsg) {
        // 回复是否可以连接
        template.convertAndSendToUser(String.valueOf(respMsg.getRemoteDeviceId()), "/topic/desktop/response", respMsg);
    }
}
